package com.demo.view;

import com.tange.base.toolkit.StringUtils;

public class IPTextHelper {
    private static final int MAX_IP_NUMBER = 255;
    private static final int MAX_CHAR_COUNT = 3;
    private String mTempIp;

    public String getTempIp() {
        return mTempIp;
    }

    public boolean isFocusInNextBtn(CharSequence s) {
        if(s.toString().trim().equals(".")){
            mTempIp = "";
            return false;
        }
        boolean contains = s.toString().trim().contains(".");
        if(s.length() >= MAX_CHAR_COUNT || contains){
            if(contains){
                mTempIp = s.toString().trim().substring(0, s.length() - 1);
            }else {
                mTempIp = s.toString().trim();
            }
            if (Integer.parseInt(mTempIp) > MAX_IP_NUMBER){
                mTempIp = String.valueOf(MAX_IP_NUMBER);
            }
            return true;
        }
        mTempIp = s.toString().trim();
        if (mTempIp.length() == 2){
            if (mTempIp.startsWith("0")){
                mTempIp = mTempIp.substring(1, s.length());
            }
        }
        return false;
    }

    public static String getValidIP(String ip){
        if (StringUtils.isEmpty(ip)){
            return "";
        }
        if (!StringUtils.isNumeric(ip)){
            return "";
        }

        while (ip.length() > 1){
            if (ip.startsWith("0")){
                ip = ip.substring(1);
            }else{
                break;
            }
        }

        if (ip.length() > MAX_CHAR_COUNT || Integer.parseInt(ip) > MAX_IP_NUMBER){
            return String.valueOf(MAX_IP_NUMBER);
        }
        return ip;
    }
}